﻿using System;
using NUnit.Framework;
using Tycho.Parser.Peg;

namespace Tycho.Parser.Tests.Peg {
    [TestFixture]
    public class ChoiceProductionSpecification {
        [Test]
        public void ParseShouldReturnTermOfSuccessfulParse () {
            var choice = new ChoiceProduction (IdentifierProduction.CreateTerminal (), IntegerProduction.CreateTerminal ());

            var source = "a";

            var result = choice.Parse (source);

            Assert.IsNotNull (result);
            Assert.AreEqual (1, result.Index);
            Assert.AreEqual ("a", ((IdentifierTerm) result.Term).Name);
        }

        [Test]
        public void ParseShouldReturnNullIfNoProductionParses () {
            var choice = new ChoiceProduction (OperatorKeywordProduction.CreateTerminal ("="), IntegerProduction.CreateTerminal ());

            var source = "a";

            var result = choice.Parse (source);

            Assert.IsNull (result);
        }

        [Test]
        public void ShouldParseLeftRecursiveRule () {
            var num = IntegerProduction.CreateTerminal ();

            ChoiceProduction expression = new ChoiceProduction (null);
            NonTerminal op = new NonTerminal ("expression", new SequenceRule (
                    new NamedRule ("left", expression),
                    new KeywordRule ("+"),
                    new NamedRule ("right", num)));
            expression.Productions = new IProduction[] {op, num};

            ParseResult result = expression.Parse ("1 + 2 + 3");
            Assert.IsNotNull (result);
        }
    }
}